package com.yuntongxun.ecdemo.voicechat.ui.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.Gift;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.listeners.IRecyclerViewItemListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.GiftsReceivedAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.RecyclerViewUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;

/**
 * Created by Administrator on 2016/12/5.
 */

public class SentGiftFragment extends BaseFragment implements ICommonViewUi, IRecyclerViewItemListener, LoadMoreClickListener, SwipeRefreshLayout.OnRefreshListener {

    private String mContent = "???";
    private static final String KEY_CONTENT = "SentGiftFragment:Content";

    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<Gift> mResultList = new ArrayList<Gift>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    public static SentGiftFragment newInstance(String content) {
        SentGiftFragment fragment = new SentGiftFragment();
        fragment.mContent = content;

        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
    }

    UserInfo userInfo;

    @Override
    protected void onFirstUserVisible() {
        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
    }

    public void refreshListView() {

        GiftsReceivedAdapter mIntermediary = new GiftsReceivedAdapter(mContext, mResultList, this);
        mIntermediary.setGiftType(GiftsReceivedAdapter.SENT);
        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {

            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected void initViewsAndEvents() {

        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new MyScrollListener());


        String data = PreferenceUtils.getPrefString(getActivity(), Contants.Preference.user_info, "");
        if (!data.equals("")) {
            JsonHelper<UserInfo> jsonHelper = new JsonHelper<UserInfo>(UserInfo.class);
            userInfo = jsonHelper.getData(data, "result");
        }

        refreshListView();


    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_gifts;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }

    @Override
    public void onItemClick(int position) {

    }

    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }

    @Override
    public void toRequest(int eventTag) {
        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            if (userInfo == null) {
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("accountName", userInfo.getAccountName());
            map.put("pageSize", "30");

            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.GIFT_SENT, map);

        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (userInfo == null) {
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("accountName", userInfo.getAccountName());
            map.put("pageSize", "30");

            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.GIFT_SENT, map);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //下拉刷新

            List<Gift> resultList = parseResult(result);

            mResultList.clear();
            mResultList.addAll(resultList);

            refreshListView();


        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            List<Gift> resultList = parseResult(result);

            mResultList.addAll(resultList);

            adapter.notifyDataSetChanged();
        }
    }

    public List<Gift> parseResult(String result) {
        JsonHelper<Gift> dataParser = new JsonHelper<Gift>(
                Gift.class);
        return dataParser.getDatas(
                result, "list");
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;

        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }
}
